package com.epro.dx.fragment;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.epro.dx.R;
import com.epro.dx.activity.ProductListActivity;
import com.epro.dx.enable.RootBrowseAdapter;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.pullview.PullToRefreshBase;
import com.epro.dx.pullview.PullToRefreshBase.Mode;
import com.epro.dx.pullview.PullToRefreshBase.OnRefreshListener2;
import com.epro.dx.pullview.PullToRefreshListView;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.content.api.CategoryService;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.impl.ProductServiceProviderImpl;
import com.weipu.common.facade.model.CatelogModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.util.AlertToast;
import com.weipu.common.util.CacheUtil;
import com.weipu.common.util.JsonFormat;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

/**
 * 商品目录页面
 * 
 * @author hjd008
 * @version [版本号, 2015-1-7]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class BrowseFragment extends BaseFragment implements OnItemClickListener {
	private static final String TAG = "BrowseFragment";

	/**
	 * 是不是第一次浏览
	 */
	private static boolean isFirstBrowseStart = true;

	/**
	 * 商品列表集合
	 */
	private List<ProductModel> products = null;

	/**
	 * 主目录列表
	 */
	private PullToRefreshListView listMainBrowse;

	/**
	 * 搜索框
	 */
//	private EditText edTxtSearch;

	/**
	 * 二级目录列表
	 */
	private ListView listNextBrowse;

	/**
	 * 三级目录列表
	 */
	private ListView listThirdBrowse;

	/**
	 * 下级目录名字
	 */
	private String[] childBrowseName;

	/**
	 * 二级目录的model
	 */
	private ArrayList<CatelogModel> childBrowseList;

	/**
	 * 三级目录的model
	 */
	private ArrayList<CatelogModel> thirdBrowseList;

	/**
	 * 主目录的model
	 */
	private static ArrayList<CatelogModel> rootBrowseList;

	/**
	 * 图片位置
	 */
	private int imgPostion = 0;

	private RootBrowseAdapter rootAdapter;

	private View rootView;

	private CategoryService categoryService;

	private String rootTime;

	private String secondChildTime;

	private String thirdChildTime;

	private String secondTitle;

	private String thirdTitle;
	
	private LinearLayout loadingLayout;
	
	private LinearLayout listLayout;
	
	private LinearLayout emptyLayout;

	private Tracker tracker;

	private EventBuilder eventBuilder;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		//集成GA
		tracker = ((DXApplication)getActivity().getApplication()).getTracker(TrackerName.APP_TRACKER);
		eventBuilder = new HitBuilders.EventBuilder();
		if (null == rootView) {
			rootView = inflate(R.layout.fragment_browse);
			categoryService = ProviderFactory.createCategoryServiceDBProvider();
			initView();
		}
		ActivityUtil.setStatusColor(getActivity(),0,rootView);
		// setInitData();
		// ViewGroup parent = (ViewGroup) rootView.getParent();
		// if (parent != null) {
		// parent.removeView(rootView);
		// }
		return rootView;
	}
	
	

	private void setInitData() {
		rootTime = StringUtil
				.getConfig(
						ServerConstant.RequestMethodNameConstant.METHOD_GETTOPCATEGORIES,
						"0");
		secondChildTime = StringUtil
				.getConfig(
						ServerConstant.RequestMethodNameConstant.METHOD_GETCHILDCATEGORIES,
						"0");
		thirdChildTime = StringUtil.getConfig("GetThirdChildCategories", "0");

		Logger.i(TAG, "onCreateView: rootTime: " + rootTime
				+ " secondChildTime: " + secondChildTime + " thirdChildTime: "
				+ thirdChildTime);
		onCreateLoding();
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if (!hidden) {
			setInitData();
		}
		super.onHiddenChanged(hidden);
	}

	/**
	 * 执行异步线程操作
	 * 
	 * @param task
	 */
	private void executeTask(AsyncTask<Void, Void, String> task) {
		AsyncTaskUtil.executeTask(task);
	}

	@Override
	public void onResume() {
		super.onResume();
		Logger.i(TAG, "----------onResume------------");
	}
	@Override
	public void onPause() {
		super.onPause();
	}
	
	/**
	 * 初始化控件
	 */
	private void initView() {
		setTitleContent(R.string.title_browse);
		topbarLeftTv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (listNextBrowse.getVisibility() == View.VISIBLE) {
					showMainListView();
				} else if (listThirdBrowse.getVisibility() == View.VISIBLE) {
					showSecondListView();
				}

			}
		});
		topbarLeftTv.setCompoundDrawablesWithIntrinsicBounds(
				R.drawable.selector_topbar_back, 0, 0, 0);
		listLayout=(LinearLayout) rootView.findViewById(R.id.list_layout);
		loadingLayout = (LinearLayout)rootView.findViewById(R.id.loading_layout);
		emptyLayout = (LinearLayout) rootView.findViewById(R.id.layout_empty);
		listMainBrowse =  (PullToRefreshListView) rootView.findViewById(R.id.list_mainbrowse);
		listMainBrowse.getRefreshableView().setSelector(R.drawable.selector_list_bg);
		// 初始化l控件
		listNextBrowse = (ListView) rootView.findViewById(R.id.list_nextbrowse);
		listThirdBrowse = (ListView) rootView
				.findViewById(R.id.list_third_browse);
		// txtNextBrowse = (TextView)findViewById(R.id.txtNextBrowse);
		// 设置子目录的单击事件
		listNextBrowse.setOnItemClickListener(this);
		// 设置list的单击事件
		listMainBrowse.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				if (null != rootBrowseList && position-1 < rootBrowseList.size()) {
					//US仓版本修改 如果点击的是
					if (rootBrowseList.get(position - 1).getBrowseID() == Constant.CategoryID.CATEGORIES_USWAREHOUSE) {

						return;
					}

					secondTitle = rootBrowseList.get(position-1).getShortName();
					eventBuilder.setCategory("ProductCategory").setAction("Go to "+secondTitle);
					tracker.send(eventBuilder.build());
					CatelogListBrowseOnClick(position-1, secondChildTime,
							rootBrowseList, 2);
				}
				
			}
		});
		listMainBrowse.setMode(Mode.PULL_FROM_START);
		listMainBrowse.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				executeTask(new LoadingHomeCategory(false));
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				
			}
		});

		listThirdBrowse.setOnItemClickListener(this);

//		edTxtSearch = (EditText) rootView.findViewById(R.id.edtxt_search);
//		edTxtSearch.setOnEditorActionListener(new OnEditorActionListener() {
//
//			public boolean onEditorAction(TextView v, int actionId,
//					KeyEvent event) {
//				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//					searchlist();
//				}
//				return false;
//			}
//		});
	}

	/**
	 * 搜索事件
	 */
//	private void searchlist() {
//		if (edTxtSearch.getText().toString().length() > 0) {
//			Intent intent = new Intent(getActivity(), SearchListActivity.class);
//			Bundle data = new Bundle();
//			data.putString("serchtxt", edTxtSearch.getText().toString().trim());
//			intent.putExtras(data);
//			startActivity(intent);
//			edTxtSearch.setText("");
//		} else {
//			// 如果没有输入任何东西。edittxt会抖动作为提示
//			Animation shake = AnimationUtils.loadAnimation(getActivity(),
//					R.anim.shake);
//			edTxtSearch.setAnimation(shake);
//		}
//	}

	/**
	 * 填充浏览LIST列表
	 * 
	 * @param rootbrowsemodel
	 *            根目录浏览列表
	 */
	private void fillDataForList(final List<CatelogModel> rootbrowsemodel) {
		// 填充主目录列表并让取得焦点
		rootAdapter = new RootBrowseAdapter(getActivity(), rootbrowsemodel,
				true);
		listMainBrowse.setAdapter(rootAdapter);
		listMainBrowse.requestFocus();
	}

	/**
	 * 父列表单击时事件
	 * 
	 * @param position
	 *            父列表Item index
	 * @param time
	 *            子列表上次数据缓存时间 用来判断缓存数据是否过期
	 * @param parentCatelogList
	 *            父列表集合数据 用来获取自列表 CategoryID
	 * @param toShowBowrseID
	 *            子列表对应的下表 一级列表为1 二级列表为2 3级列表为3
	 */
	private void CatelogListBrowseOnClick(final int position, String time,
			ArrayList<CatelogModel> parentCatelogList, int toShowBowrseID) {
		Logger.i(TAG, "CatelogListBrowseOnClick start to show son list num: "
				+ toShowBowrseID);
		// if (!listNextBrowse.isEnabled()) {
		Logger.i(TAG, "listNextBrowse enable false");
		String childCategoryID = parentCatelogList.get(position).getBrowseID()
				+ "";
		boolean isToShowSecond = toShowBowrseID == 2 ? true : false;
		if (isCategoryCacheIsHit(time, childCategoryID, toShowBowrseID)) {
			// 根据isToShowSecond显示响应列表页面
			if (isToShowSecond) {
				setChildCategoryUIWhenGetDate(childBrowseList, isToShowSecond,
						position);
			} else {
				setChildCategoryUIWhenGetDate(thirdBrowseList, isToShowSecond,
						position);
			}
		} else {
			if (isToShowSecond) {
				// new LoadingSecondCategory(position).execute();
				executeTask(new LoadingSecondCategory(position));
			} else {
				// new LoadingThirdCategory(position).execute();
				executeTask(new LoadingThirdCategory(position));
			}

		}
		// } else {
		// productIntent(rootBrowseList.get(imgPostion).getBrowseID(), null,
		// rootBrowseList.get(imgPostion).getShortName());
		// }
	}

	/**
	 * 调用产品列表
	 * 
	 * @param string
	 *            传递到下一个product的列表的目录ID
	 * @param product_list
	 *            产品列表
	 * @param str_name
	 *            目录名
	 * 
	 */
	private void productIntent(int str_id, List<ProductModel> product_list,
			String str_name) {
		Intent intent = new Intent(getActivity(), ProductListActivity.class);
		// 传递目录ID,目录名和列表对象
		ArrayList<ProductModel> prductlist = (ArrayList<ProductModel>) product_list;
		// data.putString("catalogname", str_name);
		intent.putExtra("catalogId", str_id);
		intent.putExtra("productlist", prductlist);
		intent.putExtra(Constant.TO_PRODUCTLIST_FROM, Constant.FROM_CATEGORY);
		intent.putExtra(Constant.PRODUCT_TITLE, str_name);
		startActivity(intent);
	}

	/**
	 * 显示主Listview
	 */
	private void showMainListView() {
		topbarLeftTv.setVisibility(View.INVISIBLE);
		setTitleContent(R.string.title_browse);
		listNextBrowse.setVisibility(View.GONE);
		listNextBrowse.setEnabled(false);
		listMainBrowse.setVisibility(View.VISIBLE);
		listMainBrowse.setEnabled(true);
		listThirdBrowse.setVisibility(View.GONE);
		listThirdBrowse.setEnabled(false);
	}

	/**
	 * 显示子Item Listview
	 */
	private void showSecondListView() {
		topbarLeftTv.setVisibility(View.VISIBLE);
		// 设置当前列表标题名称
		setTitleContent(secondTitle);
		listNextBrowse.setVisibility(View.VISIBLE);
		listNextBrowse.setEnabled(true);
		listMainBrowse.setVisibility(View.GONE);
		listMainBrowse.setEnabled(false);
		listThirdBrowse.setVisibility(View.GONE);
		listThirdBrowse.setEnabled(false);
	}

	/**
	 * 显示子Item Listview
	 */
	private void showThirdListView() {
		topbarLeftTv.setVisibility(View.VISIBLE);
		// 设置当前列表标题名称
		setTitleContent(thirdTitle);
		listThirdBrowse.setVisibility(View.VISIBLE);
		listThirdBrowse.setEnabled(true);
		listNextBrowse.setVisibility(View.GONE);
		listNextBrowse.setEnabled(false);
		listMainBrowse.setVisibility(View.GONE);
		listMainBrowse.setEnabled(false);
	}

	/**
	 * 启动时的加载动画
	 */
	private void onCreateLoding() {
		showMainListView();

		// 因为切换fragment 不会调用onDestory方法 所以rootBrowseList不会为空 所以需要加上失效时间
//		if (null != rootBrowseList
//				/*&& CacheUtil.getInstance().isCacheEffective(rootTime)*/) {
//			fillDataForList(rootBrowseList);
//		} else {
//			if (isCategoryCacheIsHit(rootTime,
//					ProductServiceProviderImpl.TOP_CATEGORY_DEFAULT_PARENT_ID,
//					1)) {
//				fillDataForList(rootBrowseList);
//			} else {
				// new LoadingHomeCategory().execute();
//				executeTask(new LoadingHomeCategory());
//			}
//		}
		//app 4.0 修改：先获取本地数据库如果本地没有数据及时效再访问接口获取
		ArrayList<CatelogModel> list = ProviderFactory.createCategoryServiceDBProvider().queryCategoryListByParentCategoryID(ProductServiceProviderImpl.TOP_CATEGORY_DEFAULT_PARENT_ID);
		String time = StringUtil.getConfig(ServerConstant.RequestMethodNameConstant.METHOD_GETTOPCATEGORIES, 0+"");
		long betweenTime = System.currentTimeMillis() - Long.parseLong(time);
		if(null!=list && list.size()>0 && betweenTime<(60*60*1000)){//取本地数据
			rootBrowseList = list;

			fillDataForList(rootBrowseList);
		}else{//访问接口获取数据

			executeTask(new LoadingHomeCategory(true));
		}
		
	}

	/**
	 * 点击二级目录浏览商品列表
	 * 
	 * @param myposition
	 */
	protected void thirdBroseItemClickLodiong(final int myposition) {
		// try
		// {
		// 如果接口取得没有子目录，就调用产品列表接口数据
		if (null != childBrowseList && !childBrowseList.isEmpty()) {
			productIntent(childBrowseList.get(myposition).getBrowseID(), null,
					childBrowseList.get(myposition).getShortName());
		}
	}

	/**
	 * 
	 * @param time
	 *            栏目上一次的缓存时间
	 * @param categoryID
	 *            待显示栏目ID号
	 * @param whichBrowse
	 *            1代表主目录 2代表二级目录 3代表三级目录
	 * 
	 * @return
	 */
	private boolean isCategoryCacheIsHit(String time, String categoryID,
			int whichBrowse) {
		boolean isCacheHit = false;
		Logger.i(TAG, "isCategoryCacheIsHit: " + time);
		if (TextUtils.isEmpty(time)) {
			// 为空设置为零表示还没有缓存数据
			time = "0";
		}
		Logger.i(
				TAG,
				"Browse ID:　" + whichBrowse
						+ " start to get Categories from DateBases. "
						+ System.currentTimeMillis());
		// 读取指定栏目下子目录列表
		ArrayList<CatelogModel> localDBCacheList = categoryService
				.queryCategoryListByParentCategoryID(categoryID);
		Logger.i(TAG,
				"Browse ID:　" + whichBrowse
						+ "is boot end to getTopCategories from DateBases. "
						+ System.currentTimeMillis());

		// 本地有缓存数据
		if (null != localDBCacheList && !localDBCacheList.isEmpty()) {
			// 验证缓存数据有效性
			isCacheHit = CacheUtil.getInstance().isCacheEffective(time);
			// 缓存数据不为空立即展示页面
			Logger.i(
					TAG,
					"Browse ID:　"
							+ whichBrowse
							+ "is Boot Categories.localedb.chache: loading from local success.");
			switch (whichBrowse) {
			case 1:
				rootBrowseList = localDBCacheList;
				break;
			case 2:
				childBrowseList = localDBCacheList;
				break;
			case 3:
				thirdBrowseList = localDBCacheList;
				break;

			default:
				break;
			}
		}
		return isCacheHit;
	}

	/**
	 * 主目录接口
	 * 
	 * @author hjd008
	 * @version [版本号, 2014-12-15]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	protected class LoadingHomeCategory extends AsyncTask<Void, Void, String> {
		private boolean isShowLoading;
		private LoadingHomeCategory(boolean isShowLoading){
			this.isShowLoading=isShowLoading;
		}
		@Override
		protected void onPreExecute() {
			//showWaitingDialog();
//			loadingLayout.setVisibility(View.VISIBLE);
			if(isShowLoading){
				showLoadingLayout(listLayout);
			}
			Logger.i(
					TAG,
					"start to LoadingHomeCategory "
							+ System.currentTimeMillis());
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				Logger.i(TAG, "to getTopCategories from Http Request");
				rootBrowseList = ProviderFactory.createProductProvider()
						.getTopCategories(ActivityUtil.getCustomerID(),
								OnekeyFilterLocalUtil.getFilterState(getActivity()),OnekeyFilterLocalUtil.getLocalCategoryIds(getActivity()));
			} catch (DxException e) {
				return e.getErrCode();
			}
			long currentTime = System.currentTimeMillis();
			// 第一次请求接口,数据库无数据，在请求后展示数据
			publishProgress();
			StringUtil
					.saveConfig(
							ServerConstant.RequestMethodNameConstant.METHOD_GETTOPCATEGORIES,
							currentTime + "");
			// 刷新最新缓存数据时间
			rootTime = currentTime + "";
			if (null != rootBrowseList && !rootBrowseList.isEmpty()) {
				// 清理缓存并更新本地缓存
				categoryService.clearCategory();
				for (int i = 0; i < rootBrowseList.size(); i++) {
					categoryService.saveCategoryInfo(rootBrowseList.get(i));
				}
			}
			return null;
		}

		// 展示数据
		@Override
		protected void onProgressUpdate(Void... params) {
			if(!isShowLoading){
				listMainBrowse.onRefreshComplete();
			}
			if (rootBrowseList != null && !rootBrowseList.isEmpty()) {
				showContentLayout(listLayout);
				listMainBrowse.setVisibility(View.VISIBLE);
				fillDataForList(rootBrowseList);
			}
		}

		@Override
		protected void onPostExecute(String result) {
//			hideWaitingDialog();
			if(!isShowLoading){
				listMainBrowse.onRefreshComplete();
			}
			if (null != result) {
				if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)) {
					showErrorNetLayout(listLayout);
//					netErroLayout.setVisibility(View.VISIBLE);
					emptyLayout.setVisibility(View.GONE);
//					contentLayout.setVisibility(View.GONE);
				}else{
					showErrorNetLayout(listLayout, R.string.server_busy, R.string.server_suggest);
				}
				rootView.findViewById(R.id.try_again).setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// showWaitingDialog();
//						loadingLayout.setVisibility(View.VISIBLE);
						showLoadingLayout(listLayout);
						executeTask(new LoadingHomeCategory(true));
					}
				});
			}
		}
	}

	/**
	 * 当获取到子列表数据时 刷新并显示子列表界面
	 * 
	 * @param categoryList
	 *            子列表返回数据
	 * @param isSecond
	 *            是否是显示二级列表
	 * @param position
	 *            父列表ITME index
	 */
	private void setChildCategoryUIWhenGetDate(
			ArrayList<CatelogModel> categoryList, boolean isToShowSecond,
			int position) {
		if (null != categoryList && !categoryList.isEmpty()) {
			rootAdapter = new RootBrowseAdapter(getActivity(), categoryList,
					false);
			if (isToShowSecond) {
				showSecondListView();
				// 填充子目录列表
				listNextBrowse.setAdapter(rootAdapter);
				listNextBrowse.requestFocus();
			} else {
				showThirdListView();
				// 填充子目录列表
				listThirdBrowse.setAdapter(rootAdapter);
				listThirdBrowse.requestFocus();
			}
			hideWaitingDialog();
		} else {
			Logger.i(TAG,
					"categoryList is null to load Product isToShowSecond: "
							+ isToShowSecond);
			// new ProductListAsyncTask(position,isToShowSecond).execute();
			if (isToShowSecond) {
				if(null!=rootBrowseList&&rootBrowseList.size()>position){
					productIntent(rootBrowseList.get(position).getBrowseID(),
							products, rootBrowseList.get(position).getShortName());
				}
				
			} else {
				if(null!=childBrowseList&&childBrowseList.size()>position){
					productIntent(childBrowseList.get(position).getBrowseID(),
							products, childBrowseList.get(position).getShortName());
				}
			}

		}
	}

	/**
	 * 二级目录接口
	 * 
	 * @author sjx206
	 * @version [版本号, 2014-12-19]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	protected class LoadingSecondCategory extends AsyncTask<Void, Void, String> {

		private int position;

		public LoadingSecondCategory(int position) {
			this.position = position;
		}

		@Override
		protected void onPreExecute() {
			Logger.i(TAG, "to start LoadingSecondCategory "
					+ BrowseFragment.class.getSimpleName());
//			showWaitingDialog();
			showLoadingLayout(null);
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				childBrowseList = ProviderFactory.createProductProvider()
						.GetChildCategories(
								rootBrowseList.get(position).getBrowseID());
			} catch (DxException e) {
				return e.getErrCode();
			}

			// 第一次请求接口,数据库无数据，在请求后展示数据
			publishProgress();
			long currentTime = System.currentTimeMillis();
			StringUtil
					.saveConfig(
							ServerConstant.RequestMethodNameConstant.METHOD_GETCHILDCATEGORIES,
							currentTime + "");
			secondChildTime = currentTime + "";
			if (null != childBrowseList && !childBrowseList.isEmpty()) {
				// 清理缓存并更新本地缓存
				categoryService.deleteCategoryListByParentID(rootBrowseList
						.get(position).getBrowseID() + "");
				for (CatelogModel catelogModel : childBrowseList) {
					categoryService.saveCategoryInfo(catelogModel);
				}
			}
			return null;
		}

		// 展示数据
		@Override
		protected void onProgressUpdate(Void... params) {
			showContentLayout(listLayout);
			if(listMainBrowse.getVisibility()==View.VISIBLE){
				setChildCategoryUIWhenGetDate(childBrowseList, true, position);
			}
		}

		@Override
		protected void onPostExecute(String result) {
			Logger.i(TAG, "end LoadingSecondCategory ");
//			hideWaitingDialog();
			hideLoadingLayout();
			if (null != result) {
				AlertToast.alert(getActivity(),
						ServerConstant.ReturnCode.MESSAGEMAP.get(result));
			}
			topbarLeftTv.setVisibility(View.VISIBLE);

		}

	}

	/**
	 * 三级目录接口
	 * 
	 * @author sjx206
	 * @version [版本号, 2014-12-19]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 */
	protected class LoadingThirdCategory extends AsyncTask<Void, Void, String> {

		private int thirdposition;

		public LoadingThirdCategory(int position) {
			this.thirdposition = position;
		}

		@Override
		protected void onPreExecute() {
			Logger.i(TAG, "to start LoadingThirdCategory "
					+ BrowseFragment.class.getSimpleName());
//			showWaitingDialog();
			showLoadingLayout(null);
		}

		@Override
		protected String doInBackground(Void... params) {
			try {
				if (null != childBrowseList) {
					int categoreid = childBrowseList.get(thirdposition)
							.getBrowseID();

					thirdBrowseList = ProviderFactory.createProductProvider()
							.GetChildCategories(categoreid);
				}
			} catch (DxException e) {
				return e.getErrCode();
			}

			// 第一次请求接口,数据库无数据，在请求后展示数据
			publishProgress();

			if (null != thirdBrowseList && !thirdBrowseList.isEmpty()) {
				long currentTime = System.currentTimeMillis();
				StringUtil.saveConfig("GetThirdChildCategories", currentTime
						+ "");
				thirdChildTime = currentTime + "";
				// 清理缓存并更新本地缓存
				categoryService.deleteCategoryListByParentID(childBrowseList
						.get(thirdposition).getBrowseID() + "");
				for (CatelogModel catelogModel : thirdBrowseList) {
					categoryService.saveCategoryInfo(catelogModel);
				}
			}
			return null;
		}

		// 展示数据
		@Override
		protected void onProgressUpdate(Void... params) {
			showContentLayout(listLayout);
			if(listNextBrowse.getVisibility()==View.VISIBLE){
				setChildCategoryUIWhenGetDate(thirdBrowseList, false, thirdposition);
			}
		}

		@Override
		protected void onPostExecute(String result) {
			Logger.i(TAG, "end LoadingSecondCategory ");
//			hideWaitingDialog();
			hideLoadingLayout();
			if (null != result) {
				hideLoadingLayout();
				AlertToast.alert(getActivity(),
						ServerConstant.ReturnCode.MESSAGEMAP.get(result));
			}
			topbarLeftTv.setVisibility(View.VISIBLE);

		}

	}

	/**
	 * 商品列表数据加载异步类
	 * 
	 * @version [版本号, 2012-12-17]
	 * @see [相关类/方法]
	 * @since [产品/模块版本]
	 * 
	 * @author hjd008
	 */

//	protected class ProductListAsyncTask extends AsyncTask<Void, Void, String> {
//		private int position;
//		// 是否准备显示二级列表时无二级列表数据
//		private boolean isPreShowSecond;
//
//		public ProductListAsyncTask(int position, boolean isSecond) {
//			this.position = position;
//			this.isPreShowSecond = isSecond;
//		}
//
//		@Override
//		protected void onPreExecute() {
//			showWaitingDialog();
//		}
//
//		@Override
//		protected String doInBackground(Void... params) {
//			try {
//				String mCurrencyCode = StringUtil.getConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE, getString(R.string.currency_default_currencyCode));
////				products = ProviderFactory.createProductProvider()
////						.getProductListByCategoryId(
////								1,
////								Constant.LIST_PAGE_COUNT,
////								"d=Popularity",
////								0,
////								Double.MAX_VALUE,
////								0.00,
////								Integer.valueOf(childBrowseList.get(position)
////										.getBrowseID()),currencyCode);
//				SearchModel searchModel = ProviderFactory.createProductProvider()
//						.getProductListByCategoryId(
//								1,
//								Constant.LIST_PAGE_COUNT,
//								"d=Popularity",
//								0,
//								Double.MAX_VALUE,
//								0.00,
//								Integer.valueOf(childBrowseList.get(position)
//										.getBrowseID()),mCurrencyCode);
//				products = searchModel.getProductModels();
//				currencyCode = searchModel.getCurrencyCode();
//				currencyCodeSymbol = searchModel.getCurrencyCodeSymbol();
//
//			} catch (DxException e) {
//				return e.getErrCode();
//			} catch (Exception e) {
//				Logger.e("BrowsListActivity", "ProductListAsyncTask", e);
//			}
//			return "0";
//		}
//
//		@Override
//		protected void onPostExecute(String result) {
//			hideWaitingDialog();
//			if (!"0".equals(result)) {
//				AlertToast.alert(getActivity(),
//						ServerConstant.ReturnCode.MESSAGEMAP.get(result));
//			} else {
//				if (isPreShowSecond) {
//					productIntent(rootBrowseList.get(position).getBrowseID(),
//							products, rootBrowseList.get(position)
//									.getShortName());
//				} else {
//					productIntent(childBrowseList.get(position).getBrowseID(),
//							products, childBrowseList.get(position)
//									.getShortName());
//				}
//			}
//		}
//	}

	@Override
	public void onItemClick(AdapterView<?> viewgroup, View view, int position,
			long arg3) {
		Logger.i(TAG, "mainbrowse onItemClick"+viewgroup.getId()+"  "+R.id.list_mainbrowse);
		rootTime = StringUtil
				.getConfig(
						ServerConstant.RequestMethodNameConstant.METHOD_GETTOPCATEGORIES,
						"0");
		secondChildTime = StringUtil
				.getConfig(
						ServerConstant.RequestMethodNameConstant.METHOD_GETCHILDCATEGORIES,
						"0");
		thirdChildTime = StringUtil.getConfig("GetThirdChildCategories", "0");
		switch (viewgroup.getId()) {
//		case R.id.list_mainbrowse:
//			Logger.i(TAG, "mainbrowse onItemClick");
//			// if (!listNextBrowse.isEnabled()) {
//			// imgPostion = position;
//			// }
//			if (null != rootBrowseList && position < rootBrowseList.size()) {
//				secondTitle = rootBrowseList.get(position).getShortName();
//				eventBuilder.setCategory("ProductCategory").setAction("Go to "+secondTitle);
//				tracker.send(eventBuilder.build());
//				CatelogListBrowseOnClick(position, secondChildTime,
//						rootBrowseList, 2);
//			}
//			break;
		case R.id.list_nextbrowse:
			if (null != childBrowseList && position < childBrowseList.size()) {
				thirdTitle = childBrowseList.get(position).getShortName();
				eventBuilder.setCategory("ProductCategory").setAction("Go to "+thirdTitle);
				tracker.send(eventBuilder.build());
				CatelogListBrowseOnClick(position, thirdChildTime,
						childBrowseList, 3);
			}
			break;
		case R.id.list_third_browse:
			if (null != thirdBrowseList && position < thirdBrowseList.size()) {
				CatelogModel clickCatelog = thirdBrowseList.get(position);
				if (null != clickCatelog) {
					eventBuilder.setCategory("ProductCategory").setAction("Go to "+clickCatelog.getShortName());
					tracker.send(eventBuilder.build());
					productIntent(clickCatelog.getBrowseID(), null,
							clickCatelog.getShortName());
				}
			}
			break;

		default:
			break;
		}

	}
	
    
//    private void showContentLayout(View view){
//    	if(null!=view){
//    		view.setVisibility(View.VISIBLE);
//    	}
//    	if(null!=emptyLayout){
//        	emptyLayout.setVisibility(View.GONE);
//        }
//        if(null!=loadingLayout){
//        	loadingLayout.setVisibility(View.GONE);
//        }
//    }
    
//    private void showEmptyLayout(View view){
//    	if(null!=view){
//    		view.setVisibility(View.GONE);
//    	}
//    	if(null!=emptyLayout){
//        	emptyLayout.setVisibility(View.VISIBLE);
//        }
//        if(null!=loadingLayout){
//        	loadingLayout.setVisibility(View.GONE);
//        }
//    }
    
    @Override
    protected View setLeftBtnContent(Boolean isBackIcon, int resId) {
    	if(loadingLayout.getVisibility()==View.VISIBLE){
    		loadingLayout.setVisibility(View.GONE);
    	}
    	return super.setLeftBtnContent(isBackIcon, resId);
    }

}
